package com.lenovo.smarttraffic.ui.fragment.stage3;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.database.SensorDataDB;
import com.lenovo.smarttraffic.ui.fragment.MyBaseFragment;

import org.litepal.LitePal;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class RealEnvFragment extends MyBaseFragment {

    private Handler handler = new Handler();

    private LineChart lineChart;
    private List<Entry> entries = new ArrayList<>();
    private LineData lineData = new LineData();
    private LineDataSet dataSet;

    private List<Integer> colors = new ArrayList<>();

    private Context context;

    private String type = "";

    private List<Integer> xTime = new ArrayList<>();

    private int time = 0;

    public RealEnvFragment setType(String type) {
        this.type = type;
        return this;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_realtime, container, false);
        lineChart = view.findViewById(R.id.line_chart);
        TextView title = view.findViewById(R.id.title);
        title.setText(type);

        return view;
    }


    private void initChart() {
        Description description = new Description();
        description.setText("(秒)");
        description.setTextSize(15);
        description.setTextAlign(Paint.Align.CENTER);//提示框的文本对齐
        lineChart.setDescription(description);

        dataSet = new LineDataSet(entries, type);//将数据赋值到你的线条上
        dataSet.setColor(Color.GRAY);
        dataSet.setDrawCircleHole(false);
        dataSet.setDrawValues(false);
        dataSet.setDrawIcons(false);
        dataSet.setLineWidth(3);
        dataSet.setCircleRadius(5);

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setTextSize(15);
        xAxis.setTextColor(Color.BLACK);
        //xAxis.setLabelRotationAngle(45);//x轴标签旋转45度
        xAxis.setAxisLineWidth(2);
        xAxis.setAvoidFirstLastClipping(true);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//x轴显示在底下
        xAxis.setDrawGridLines(false);//隐藏x轴辅助线
        //x轴格式转换
        xAxis.setValueFormatter((value, axis) -> {
            return xTime.get((int) value) + "";
        });

        YAxis yAxis = lineChart.getAxisLeft();
        yAxis.setTextSize(15);
        yAxis.setTextColor(Color.BLACK);
        yAxis.setDrawAxisLine(false);//隐藏x轴边界线
        yAxis.setDrawGridLines(false);
        yAxis.setLabelCount(1, true);
        try {//反射使Y轴标签强制为1
            Field field = yAxis.getClass().getSuperclass().getDeclaredField("mLabelCount");
            field.setAccessible(true);
            field.set(yAxis, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }

        yAxis.setAxisLineWidth(2);
        //yAxis.setValueFormatter((value, axis) -> 200 + "");


        lineChart.getAxisRight().setEnabled(false);//隐藏y轴辅助线
        lineChart.setHighlightPerTapEnabled(false);
        lineChart.setHighlightPerDragEnabled(false);
        lineChart.setDoubleTapToZoomEnabled(false);
        lineChart.setDragDecelerationEnabled(true);
        lineChart.setPinchZoom(true);


        lineData.addDataSet(dataSet);//每加一条就add一次
        lineChart.setData(lineData);//把线条设置给你的lineChart上
        lineChart.invalidate();//刷新

        runnable.run();
        refresh();
    }

    private void refresh() {
        handler.postDelayed(() -> {
            runnable.run();
            refresh();
        }, 3000);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            List<SensorDataDB> dbList = LitePal.order("date desc").find(SensorDataDB.class);
            SensorDataDB sensorDataDB = dbList.get(dbList.size() - 1);
            time += 3;
            xTime.add(time);
            int y = Double.valueOf(getData(sensorDataDB)).intValue();

            entries.add(new Entry(entries.size(), y));
            colors.add(y > 200 ? Color.RED : Color.GREEN);
            dataSet.setCircleColors(colors);
            dataSet.notifyDataSetChanged();
            lineData.notifyDataChanged();
            lineChart.notifyDataSetChanged();
            lineChart.invalidate();
        }
    };

    private String getData(SensorDataDB db) {
        switch (type) {
            case "温度":
                return db.getTemperature();
            case "湿度":
                return db.getHumidity();
            case "光照":
                return db.getLightIntensity();
            case "CO2":
                return db.getCo2();
            case "PM2.5":
            case "PM2.5指数":
                return db.getPm25();
            case "道路状态":
                return db.getRoadState();
            default:
                return "-1";
        }
    }

    @Override
    public void onViewFinished() {
        initChart();
    }
}
